package com.tdf.lolpanel.controller;

import com.tdf.lolpanel.context.BaseContext;
import com.tdf.lolpanel.dto.UserRegisterDTO;
import com.tdf.lolpanel.dto.UserLoginDTO;
import com.tdf.lolpanel.entity.User;
import com.tdf.lolpanel.result.Response;
import com.tdf.lolpanel.service.UserService;
import com.tdf.lolpanel.constant.JwtConstant;
import com.tdf.lolpanel.utils.JwtUtils;
import com.tdf.lolpanel.vo.UserLoginVO;
import io.jsonwebtoken.Jwt;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Tag(name = "用户相关接口")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Response<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录: {}", userLoginDTO);

        User user = userService.login(userLoginDTO);

        // 登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtConstant.UID, user.getId());          // id
        claims.put(JwtConstant.STATUS, user.getStatus());   // 用户类型
        claims.put(JwtConstant.UNAME, user.getUsername());  // 名称
        String token = JwtUtils.createJWT(
                JwtConstant.secretKey,
                JwtConstant.ttl,
                claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .lolname(user.getLolname())
                .token(token)
                .build();
        return Response.success(userLoginVO);
    }

    /**
     * 退出
     */
    @PostMapping("/logout")
    @Operation(summary = "用户退出")
    public Response<String> logout(){
        log.info("用户{}(uid:{})退出", BaseContext.get(JwtConstant.UNAME), BaseContext.get(JwtConstant.UID))
        Integer uid = Integer.valueOf(BaseContext.get(JwtConstant.UID));
        userService.logout(uid);

        return Response.success();
    }

    /**
     * 添加用户
     */
    @PostMapping
    @Operation(summary = "新增用户")
    public Response add(@RequestBody UserRegisterDTO userRegisterDTO) {
        log.info("添加用户: {}", userRegisterDTO);
        userService.add(userRegisterDTO);
        return Response.success();
    }

}


